<template>
  <PageWrapper title="考核文件">
    <a-layout>
      <a-layout-sider width="200" style="background: #fff">
        <a-menu
          v-model:selectedKeys="selectedKeys"
          v-model:openKeys="openKeys"
          mode="inline"
          :items="items"
          @click="itemClick"
          :style="{ height: '100%', borderRight: 0 }"
        />
      </a-layout-sider>
      <a-layout style="padding: 0 24px 24px">
        <a-layout-content
          :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
        >
          <div id="content">
            <div id="content-title" v-if="!showContent"></div>
            <div v-if="showContent">
              <div class="file-area">
                <div
                  style="
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;
                    padding-right: 20px;
                  "
                >
                  <span style="padding-right: 10px; font-weight: bold" v-if="pdfUrl">{{
                    fileName
                  }}</span>
                  <a-upload
                    v-if="isCurrentUser"
                    v-model:file-list="fileList"
                    action="http://localhost:3000/upload"
                    maxCount="1"
                    :showUploadList="false"
                    :before-upload="beforeUpload"
                    @change="handleChange"
                  >
                    <a-button style="margin-right: 8px"> 上传 </a-button>
                  </a-upload>
                  <a-button type="primary" @click="downloadFile" v-if="pdfUrl"
                    ><a
                      :href="`http://localhost:3000/downloadFile?filePath=${pdfUrl}`"
                      :download="fileName"
                      style="color: white; text-decoration: none"
                      >下载</a
                    ></a-button
                  >
                </div>
              </div>
              <div>
                <PdfContainer v-if="pdfUrl" :url="pdfUrl" :key="pdfUrl" />
              </div>
            </div>
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, VueElement, reactive, h } from 'vue';
  import { PageWrapper } from '@/components/Page';
  import { FieldTimeOutlined } from '@ant-design/icons-vue';
  import { useDownloadFileApi, useFileDataApi } from '@/api/demo/assess';
  import { useUserStore } from '@/store/modules/user';
  import { PdfContainer } from '@/components/Pdf';
  import { message, Upload } from 'ant-design-vue';
  import type { ItemType } from 'ant-design-vue';

  const fileList = ref([]);
  const selectedKeys = ref<string[]>([]);
  const openKeys = ref<string[]>([]);
  const showContent = ref(false);
  const itemFlag = ref(false);
  const pdfUrl = ref('');
  const fileName = ref('');
  const isCurrentUser = ref(false);
  const items: ItemType[] = reactive([]);
  const fileData = ref<any>([]);

  function getItem(
    label: VueElement | string,
    key: string,
    icon?: any,
    children?: ItemType[],
    type?: 'group',
  ): ItemType {
    return {
      key,
      icon,
      children,
      label,
      type,
    } as ItemType;
  }

  const getFileData = async () => {
    const data = await useFileDataApi({ userid: useUserStore().userInfo?.userId });
    console.log('🚀 ~ getFileData ~ data:', data);
    if (data.data.success && data.data.message === 'Success') {
      fileData.value = data?.data?.fileData.map((item) => {
        const array = Array.from(Object.keys(item.stageData), (key) => ({
          name: key,
          resources: item.stageData[key]?.resources,
        }));
        item.stageData = array;
        return item;
      });
      console.log('fileData', fileData.value);
      items.splice(0, items.length);
      fileData.value.forEach((item, index) => {
        const items1: ItemType[] = [];
        item.stageData.forEach((i, idx) => {
          items1.push(getItem(i.name, `${index}-${idx}`));
        });
        items.push(getItem(item.stageName, index, () => h(FieldTimeOutlined), items1));
      });
      console.log('🚀 ~ getFileData ~ fileData:', items);
    }
  };

  getFileData();

  const itemClick = ({ keyPath }) => {
    const index = keyPath[keyPath.length - 1];
    let indexArray = index.split('-');
    const clickItem = fileData.value[indexArray[0]]?.stageData?.[indexArray[1]];
    console.log('🚀 ~ itemClick ~ clickItem:', clickItem);
    showContent.value = true;
    itemFlag.value = true;
    pdfUrl.value = clickItem.resources[0] || '';
    console.log('🚀 ~ itemClick ~ pdfUrl.value:', pdfUrl.value);
    const array = pdfUrl.value.split('\\') || [];
    fileName.value = array[array.length - 1];
    const name = clickItem.name;
    isCurrentUser.value = name === useUserStore()?.userInfo?.username;
  };

  const beforeUpload = (file) => {
    const isPDF = file.type === 'application/pdf';
    if (!isPDF) {
      message.error(`${file.name}不是pdf文件`);
    }
    return isPDF || Upload.LIST_IGNORE;
  };

  const handleChange = ({ file, fileList }) => {
    console.log('🚀 ~ handleChange ~ file:', file);
    if (file.status !== 'uploading') {
      console.log(file, fileList);
    }
    if (file.status === 'done') {
      pdfUrl.value = file?.response?.filePath;
      const array = pdfUrl.value.split('\\') || [];
      fileName.value = array[array.length - 1];
      console.log('🚀 ~ handleChange ~ pdfUrl.value:', pdfUrl.value);
    }
  };

  const downloadFile = () => {
    useDownloadFileApi({ filePath: pdfUrl.value });
  };
</script>
<style scoped>
  #components-layout-demo-top-side-2 .logo {
    width: 120px;
    height: 31px;
    margin: 16px 24px 16px 0;
    float: left;
    background: rgb(255 255 255 / 30%);
  }

  .ant-row-rtl #components-layout-demo-top-side-2 .logo {
    margin: 16px 0 16px 24px;
    float: right;
  }

  .site-layout-background {
    background: #fff;
  }

  .file-area {
    margin-bottom: 10px;
  }
</style>
